package com.creative.accountsdk.net;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.creative.accountsdk.AccountSdk;
import com.creative.accountsdk.DataCenter;
import com.creative.accountsdk.UserData;
import com.creative.util.EncodeUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by yinjialiang on 15-6-18.
 */
public abstract class Protocol {
    public final static int TIMEOUT_CONNECTION = 8000;// 连接超时时间
    public final static int TIMEOUT_SOCKET = 8000;// socket超时

    /**内网测试服*/
    public final static int SERVER_TEST = 0;
    /**外网测试服*/
    public final static int SERVER_PUBLIC_TEST = 1;
    /**正式服*/
    public final static int SERVER_PUBLIC = 2;
    /**当前连接的服务器*/
    public final static int SERVER = SERVER_TEST;

    public final static String URL_PUBLIC = "http://duba.wawayaya.com/pc/"; //公网
    public final static String URL_PUBLIC_TEST = "http://testduba.wawayaya.com/pc/"; //公网测试
    public final static String URL_TEST = "http://10.135.195.150/pc/"; //内网测试

    public static String getUrlPrefix()
    {
        switch(SERVER)
        {
            case SERVER_TEST:
                return URL_TEST;
            case SERVER_PUBLIC_TEST:
                return URL_PUBLIC_TEST;
            case SERVER_PUBLIC:
                return URL_PUBLIC;
        }
        return null;
    }
    /**
     * 服务器返回之成功
     */
    public final static int RETURN_SUCCESS = 1;
    public final static int RETURN_Failure = 0;
    private final static String TAG = "Protocol";
    /**
     * RETURN_SUCCESS表示成功
     */
    protected int returnCode;
    protected String returnMessage;

    public Protocol()
    {
//        Log.d(getClass().getSimpleName(), getClass().getName());
    }

    public static RequestParams createParams() {
        return createParams(true);
    }

    public static RequestParams createParams(boolean needUID) {
        RequestParams params = new RequestParams();
        if (DataCenter.IMEI != null) {
            params.put("device", DataCenter.IMEI);
        }
        long ts = System.currentTimeMillis();
        params.put("ts", ts);
        params.put("sign", getSign(ts));
        params.put("appid", AccountSdk.getInstance().getAppID());
        params.put("locale", DataCenter.LOCAL);
        UserData userData = UserData.getInstance();
        if (userData != null && userData.exist()) {
            params.put("uid", userData.getUid());
            params.put("token", userData.getToken());
        }
        params.put("os", "android");
        params.put("ver", DataCenter.VERSION_CODE);
        return params;
    }

    public static String getSign(long time) {
        if (DataCenter.IMEI != null) {
            return EncodeUtil.encodeByMD5(time + DataCenter.IMEI);
        }
        return EncodeUtil.encodeByMD5(time + "");
    }

    public abstract RequestParams getParams();

    /**
     * 例子：return URL_PREFIX + "test.action";
     *
     * @return
     */
    public abstract String getUrl();

    protected abstract void parseReturnMap(JSONObject returnMap);

    public boolean parse(JSONObject  response, Context context) {
        if (parse(response)) {
            return true;
        }
        toastResult(context);
        return false;
    }

    public final JSONObject optReturnMap(JSONObject jsonObject) {
        return jsonObject.optJSONObject("retMap");
    }

    public final int optReturnCode(JSONObject jsonObject) {
        return jsonObject.optInt("retCode");
    }

    public final String optReturnMessage(JSONObject jsonObject) {
        return jsonObject.optString("retMsg");
    }

    /**
     * 预处理
     *
     * @param response
     * @return
     */
    public final boolean preparse(JSONObject response) {
        returnCode = optReturnCode(response);
        if (returnCode == RETURN_SUCCESS) {
            return true;
        }
        returnMessage = optReturnMessage(response);
        return false;
    }

    public boolean parse(JSONObject  response) {
        Log.d(this.getClass().getSimpleName(), "class = " + getClass().getName());
        Log.d(this.getClass().getSimpleName(), "response = " + response);

        if (preparse(response)) {
            JSONObject returnMap = optReturnMap(response);
            if (returnMap != null) {
                parseReturnMap(returnMap);
            }
            return true;
        }
        return false;
    }

    public void toastResult(Context context) {
        if(context != null) {
            Toast.makeText(context, returnMessage, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 打印URL地址
     */
    public void debugUrl(AsyncHttpClient httpClient) {
        Log.d(getClass().getSimpleName(), "网络请求url = " + httpClient.getUrlWithQueryString(true, getUrl(), getParams()));
    }
}
